//
//  ZJRJViewController.m
//  Estate
//
//  Created by heyong on 16/5/26.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define CELL_HEIGHT 46.0f
#import "RJTableCell.h"
#import "addZJRJViewController.h"
#import "ZJRZDetailViewController.h"

#import "ZJRJViewController.h"

@interface ZJRJViewController ()<UITableViewDelegate,UITableViewDataSource>

//表格
@property(strong, nonatomic)UITableView *tableView;
//数据
@property(strong ,nonatomic)NSMutableArray *dataArray;
//添加按钮
@property (strong, nonatomic)UIButton *addBtn;


@end


@implementation ZJRJViewController

- (NSMutableArray *)dataArray{
    if(_dataArray==nil){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-44-49-50*BIZ)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [_tableView registerNib:[UINib nibWithNibName:@"RJTableCell" bundle:nil] forCellReuseIdentifier:@"RJCell"];
        _tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    }
    
    return _tableView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.view.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    self.tableView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    [self createView1];
    [self initDataSource];
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"Refresh_zj_rj" object:nil];
    
}

- (void)refresh:(id)sender{
    [self.dataArray removeAllObjects];
    [self initDataSource];
    [self.tableView reloadData];
    
}

- (void)createView1{
    self.addBtn=[[UIButton alloc]initWithFrame:CGRECTS(260, 360, 100, 100)];
    [_addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [self.view addSubview:_addBtn];
    [_addBtn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -添加日记
- (void)clickBtn{

    if([LSUtility isExistAndType]){
        //判断日记是否同步
        NSDictionary *diary= [self queryDiaryDataSyn];
        
        if(diary[@"dataSyn"]){
            [LSUtility showToastWithMessage:@"该日记已经同步到服务器端，不可更改！" inView:self.navigationController.view Andtime:1.5];
        }else{
            addZJRJViewController *addCtr=[[addZJRJViewController alloc]init];
            addCtr.flag = @"add";
            addCtr.isEdit = YES;
            //有了之后重新添加需要传ID
            addCtr.ids = diary[@"ID"];
            [self.navigationController pushViewController:addCtr animated:YES];
        }
    }else
    {
        addZJRJViewController *addCtr=[[addZJRJViewController alloc]init];
        addCtr.flag=@"add";
        addCtr.isEdit=YES;
        [self.navigationController pushViewController:addCtr animated:YES];
    }
}

//判断日记是否同步
-(NSDictionary *)queryDiaryDataSyn{
    NSString *sql=[NSString stringWithFormat:@"SELECT id,date(DIARY_TIME),date(CREATE_TIME) ,LOCAL_MODIFY_STATE FROM WORK_DIARY WHERE  date(DIARY_TIME) = '%@' AND DIARY_USER='%@'",[LSUtility dateNow],USERID];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result=[db executeQuery:sql];
    BOOL dataSyn=YES;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    while ([result next]) {
        
        NSString *LOCAL_MODIFY_STATE=[result stringForColumn:@"LOCAL_MODIFY_STATE"];
        NSString *ID=[result stringForColumn:@"ID"];

        if([LOCAL_MODIFY_STATE isEqualToString:@"ADD"]||[LOCAL_MODIFY_STATE isEqualToString:@"MOD"]){
            dataSyn=NO;
        }
        [dic setValue:@(dataSyn) forKey:@"dataSyn"];
        [dic setValue:ID forKey:@"ID"];

    }
    [db close];
    return dic;
}

#pragma mark -初始化数据
//初始化数据
- (void)initDataSource
{
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
   
        NSString *sqlStr=[NSString stringWithFormat:@"select *,substr(DIARY_TIME,1,10) AS Day from WORK_DIARY WHERE PRO_ID = '%@'  ORDER BY DIARY_TIME desc", PROID];
        
        FMResultSet *results=[db executeQuery:sqlStr];
        //查询到记录
        NSMutableArray *DetailArr=[NSMutableArray array];
        
        while ([results next]) {
            //id
            NSString *ids=[results stringForColumn:@"ID"];
            //获得天
            NSString *day=[results stringForColumn:@"Day"];
            //标题
            NSString *title=[NSString stringWithFormat:@"%@日记",day];
            //时间
            NSString *time=[results stringForColumn:@"CREATE_TIME"];
            //状态
            int state=[results intForColumn:@"REVIEW_STATE"];
            //记录人
            NSString *logUserId=[results stringForColumn:@"DIARY_USER"];
            NSString *recordName=[LSUtility getuserIdByUserName:logUserId][@"REAL_NAME"];
            NSString *yearAndmonth = [time substringToIndex:7];
            NSDictionary *dict = @{@"id":ids,@"title":title,@"time":time,@"state":[NSString stringWithFormat:@"%i",state],@"recordName":DEFISNUL(recordName) ,@"recordId":logUserId,@"yearAndmonth":yearAndmonth};
            [DetailArr addObject:dict];
        }
    
       NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (NSDictionary *diaryDic in DetailArr) {
            if ([dic.allKeys containsObject:diaryDic[@"yearAndmonth"]]) {
                NSMutableArray *array = dic[diaryDic[@"yearAndmonth"]];
                [array addObject:diaryDic];
            }else{
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:diaryDic];
                [dic setValue:array forKey:diaryDic[@"yearAndmonth"]];
            }
        }
    
        NSArray *allKeys = [dic allKeys];
        for (NSString *key in allKeys) {
            NSMutableArray *array = dic[key];
            if (array.count>0) {
                //创建一个字典 包含数组，分组名，是否展开的标示
                NSArray *yearAndmonths = [key componentsSeparatedByString:@"-"];
                //拼接成标题
                NSString *tiemAndCount=[NSString stringWithFormat:@"%@年%@月(%zd条)",yearAndmonths[0],yearAndmonths[1],array.count];
                NSMutableDictionary *dicdiary =[[NSMutableDictionary alloc] initWithObjectsAndKeys:array,DIC_ARARRY,tiemAndCount,DIC_TITILESTRING,[NSNumber numberWithInt:0],DIC_EXPANDED,nil];                //将字典加入数组
                [self.dataArray addObject:dicdiary];
            }
        }
    
    
    
    [db close];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic=[_dataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section=indexPath.section;
    long row=indexPath.row;
    //得到改组下信息
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *dataD=array[row];
    
    RJTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"RJCell" forIndexPath:indexPath];
    cell.title.text=[dataD objectForKey:@"title"];
    cell.time.text=[dataD objectForKey:@"time"];
    cell.name.text=[dataD objectForKey:@"recordName"];
    [cell setType:[dataD objectForKey:@"state"]];
    
    return cell;
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH,(CELL_HEIGHT-5)*BIZ)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题

    [eButton setTitle:[[self.dataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:16.*BIZ];
    
    //设置button的图片和标题的相对位置
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    UIImage *image=eButton.imageView.image;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, image.size.width)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0, eButton.titleLabel.bounds.size.width+20, 0, -eButton.titleLabel.bounds.size.width)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 5;
    }else{
        return 0.1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60*BIZ;
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *dataD=array[indexPath.row];
    //传入角色，加载不同的数据源
    BOOL isZJ=[LSUtility getDiaryType:dataD[@"id"]];
    
    //总监日记
    if (isZJ) {
        addZJRJViewController *zj=[[addZJRJViewController alloc]init];
        zj.ids=dataD[@"id"];
        zj.isEdit=NO;
        zj.flag=@"look";
        [self.navigationController pushViewController:zj animated:YES];
        
    // 评阅监理日记
    } else {
        ZJRZDetailViewController *detail = [[ZJRZDetailViewController alloc]init];
        //传入id
        detail.diaryId=dataD[@"id"];
        //阅读页
        detail.flag=@"look";
        detail.identity=@"";
        detail.state=[dataD objectForKey:@"state"];
        [self.navigationController pushViewController:detail animated:YES];
    }
}

#pragma mark -- 内部调用
//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[_dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
    
}

//返回指定节是否是展开的

-(int)isExpanded:(long)section{
    NSDictionary *dic=[_dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}



@end
